package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"learn-sys/cache"
	"learn-sys/model"
	"learn-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	var user model.User
	model.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "密码正确,登录成功",
	})
	return
}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.RoleNode{
		Nid: nid,
		Rid: rid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.uid = 1
	*/
	var roles []model.Role
	model.DB.
		Joins(" LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid =?", uid).
		Find(&roles)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": roles,
	})

}
func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	/*
			SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var nodes []model.Node
	model.DB.
		Joins(" LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid =?", rid).
		Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": nodes,
	})
}

func AfterAdd(c *gin.Context) {
	afters_types := c.PostForm("afters_types")
	afters_name := c.PostForm("afters_name")
	data := model.After{
		Afters_types: afters_types,
		After_name:   afters_name,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}
func OrderAdd(c *gin.Context) {
	aid, _ := strconv.Atoi(c.PostForm("aid"))
	form_address := c.PostForm("form_address")
	to_address := c.PostForm("to_address")
	data := model.Order{
		Aid:          aid,
		From_address: form_address,
		To_address:   to_address,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	/*
		SELECT
		  orders.id AS Oid,
		  orders.from_address AS From_address,
		  orders.to_address AS To_address,
		  afters.afters_types AS Afters_types,
		  afters.after_name AS After_name
		FROM
		  orders
		  LEFT JOIN afters ON afters.id = orders.aid
	*/
	var orderlist []model.OrderList
	redis_key := "list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		model.DB.Table("orders").
			Select("orders.id AS Oid",
				"orders.from_address AS From_address",
				"orders.to_address AS To_address",
				"afters.afters_types AS Afters_types",
				"afters.after_name AS After_name",
			).
			Joins("LEFT JOIN afters ON afters.id = orders.aid").
			Offset(offset).Limit(size).Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  orderlist,
		"total": total,
	})
}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  orders.id AS Oid,
		  orders.from_address AS From_address,
		  orders.to_address AS To_address,
		  afters.afters_types AS Afters_types,
		  afters.after_name AS After_name
		FROM
		  orders
		  LEFT JOIN afters ON afters.id = orders.aid
	*/
	var orderlist []model.OrderList
	redis_key := "list_id" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		model.DB.Table("orders").
			Select("orders.id AS Oid",
				"orders.from_address AS From_address",
				"orders.to_address AS To_address",
				"afters.afters_types AS Afters_types",
				"afters.after_name AS After_name",
			).
			Joins("LEFT JOIN afters ON afters.id = orders.aid").
			Where("orders.id=?", id).Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  orderlist,
		"total": total,
	})
}
